package com.xwj.nio.reactor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * 反应器
 * @author xwj
 * @date 2020/6/10
 */
public class EchoServerReactor implements Runnable {
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;

    public static void main(String[] args) throws IOException {
        new Thread(new EchoServerReactor()).start();
    }

    public EchoServerReactor() throws IOException {
        // 获取选择器
        selector = Selector.open();
        // 开启ServerSocketChannel监听通道
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
//        serverSocketChannel.socket().bind(new InetSocketAddress(8888));
        serverSocketChannel.bind(new InetSocketAddress(8888));
        SelectionKey sk = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        // 绑定AcceptorHandler处理器到SelectionKey
        sk.attach(new AcceptorHandler());
    }

    /**
     * 轮询和分发事件
     */
    @Override
    public void run() {
        try {
            while(!Thread.interrupted()) {
                selector.select();
                Iterator<SelectionKey> selectionKey = selector.selectedKeys().iterator();
                while (selectionKey.hasNext()) {
                    // 反应器负责处理dispatch接收到的事件
                    SelectionKey sk = selectionKey.next();
                    dispatch(sk);
                    selectionKey.remove();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dispatch(SelectionKey sk) {
        Runnable runnable = (Runnable) sk.attachment();
        // 调用之前attach绑定到选择键的handler处理器对象
        if(runnable != null) {
            runnable.run();
        }
    }

    /**
     * Handler：新连接处理器
     */
    class AcceptorHandler implements Runnable {

        @Override
        public void run() {
            try {
                SocketChannel sc = serverSocketChannel.accept();
                if(sc != null) {
                    new EchoHandler(selector, sc);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
